#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //设置这个标题
    this->setWindowTitle("服务器");
    //创建出套接字对象
    socket = new QUdpSocket(this);
    //连接信号槽
    connect(socket,&QUdpSocket::readyRead,this,&Widget::processRequest);
    //绑定端口号
    bool ret = socket->bind(QHostAddress::Any,9090);
    if(!ret)
    {
        //绑定失败
        QMessageBox::critical(this,"服务器绑定出错",socket->errorString());
        return;
    }

    ui->listWidget->addItem("服务器启动：");
}

Widget::~Widget()
{
    delete ui;
}

//服务器逻辑
void Widget::processRequest()
{
    //1.读取请求并解析
    const QNetworkDatagram& requestDatagram = socket->receiveDatagram();
    QString request=requestDatagram.data();
    //2.根据请求计算响应
    const QString& response=process(request);
    //3.构建响应数据报
    QNetworkDatagram responseDatagram(response.toUtf8(),requestDatagram.senderAddress(),requestDatagram.senderPort());
    //4.把响应写给客户端
    socket->writeDatagram(responseDatagram);
    //5.显示到界面上
    QString saveText = "[" + requestDatagram.senderAddress().toString() + ": "+QString::number(requestDatagram.senderPort())
            +"] #req "+request+ " #resp "+response;
    ui->listWidget->addItem(saveText);
}

//业务处理
QString Widget::process(const QString& request)
{
    //业务处理
    //.........省略
    //返回
    return request;
}

